相关疑难解决方法(0)

传递const char*作为模板参数

为什么你不能在这里传递文字字符串?我使用了一个非常轻微的解决方法.

template<const char* ptr> struct lols {
    lols() : i(ptr) {}
    std::string i;
};
class file {
public:
    static const char arg[];
};
decltype(file::arg) file::arg = __FILE__;
// Getting the right type declaration for this was irritating, so I C++0xed it.

int main() {
    // lols<__FILE__> hi; 
    // Error: A template argument may not reference a non-external entity
    lols<file::arg> hi; // Perfectly legal
    std::cout << hi.i;
    std::cin.ignore();
    std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)

c++ string templates

28
推荐指数
4
解决办法
3万
查看次数

为什么模板非类型参数不能是类类型

class Example {

   // ...
};

template <typename T, Example ex>  //Error
class MyExample{

   // ...
};
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么模板非类型参数不能是类类型?

我得到的错误是

error: ‘class Example’ is not a valid type for a template constant parameter

c++ templates types

7
推荐指数
3
解决办法
5388
查看次数

将数组元素传递给模板

我认为下面的代码是不言自明的。我可以轻松地将静态变量传递给模板参数,并且它按预期工作。使用静态数组将清理代码,因此它看起来更好,但不幸的是,由于我在注释中粘贴的错误,它无法编译。请注意,它是由带有 c++17 标志的 gcc 10.2 编译的。所以问题是如何将数组元素传递给模板。

#include <iostream>
#include <vector>
#include <tuple>

using DataTransfer = std::tuple<char, int>;
using DataPool     = std::vector<DataTransfer>;

typedef struct Event
{
    DataPool dataPool;
    const char* description;
} Event;

template <Event& event>
class EventTransmitter
{
    public:
    EventTransmitter()
    {
        std::cout<<event.description<<"\n";
    }
};

static Event ev1{ {{'d', 4}, {'a', 1}}, "Description 1"};
static Event ev2{ {{'g', 7}, {'b', 6}}, "Description 2"};

static Event evs[2] {
    { {{'d', 4}, {'a', 1}}, "Description 1"},
    { {{'g', 7}, {'b', 6}}, "Description 2"} …
Run Code Online (Sandbox Code Playgroud)

c++ arrays templates c++17

6
推荐指数
1
解决办法
88
查看次数

在模板专业化方面,如何将浮点数视为非类型模板参数

考虑以下程序

#include <iostream>
#include <limits>

template<float f>
void fun(){
    std::cout << "val: " << f << "\n";
}

template<>
void fun<std::numeric_limits<float>::signaling_NaN()>(){
    std::cout << "sn\n";
}

int main() {
    static_assert(std::numeric_limits<float>::signaling_NaN()!=std::numeric_limits<float>::signaling_NaN());
    fun<std::numeric_limits<float>::signaling_NaN()>();
    fun<std::numeric_limits<float>::quiet_NaN()>();
}
Run Code Online (Sandbox Code Playgroud)

它打印出:

Sn
值:nan

因此,这让我认为编译器在考虑模板专门化时会对浮点数进行按位比较(请参阅参考资料static_assert)。它是否正确?

我尝试阅读 13.4.3 模板非类型参数,但似乎没有在那里指定,但我真的很难阅读标准,所以我可能会遗漏一些明显的东西。

c++ ieee-754 c++20 non-type-template-parameter

5
推荐指数
0
解决办法
120
查看次数