我有一个带有静态常量变量的类,我需要根据模板参数中的变量类型对其进行不同的初始化。有没有办法在没有专门化的情况下做到这一点?
在我的头文件中,我有:
template<class Item>
class CircularQueue {
public:
static const Item EMPTY_QUEUE;
...
尝试在 .cpp 文件中初始化它:
template<typename Item> const Item CircularQueue<Item>::EMPTY_QUEUE = Item("-999");
我希望它初始化为 -999,无论它是 int、double 还是字符串。但是,在上面的代码中,我收到“从 'const char' 到 'int' 的转换会丢失精度 [-fpermissive]”错误。
最佳答案
提供一个使用可以专门化的单独帮助程序类的示例,而不必专门化整个模板类,因为您提到您希望看到这种方法的示例。
只需声明一个单独的模板类来设置默认值,并将其专门用于 std::string
。
template<class Item> class defaultItem {
public:
static constexpr Item default_value() { return -999; }
};
template<> class defaultItem<std::string> {
public:
static constexpr const char *default_value() { return "-999"; }
};
如果您的 C++ 编译器不是最新版本,则不必使用 constexpr
关键字。如果需要,您还可以为 const char *
而不是 std::string
定义相同的特化。
然后,您的主类只需将 EMPTY_QUEUE
定义为:
template<typename Item>
const Item CircularQueue<Item>::EMPTY_QUEUE =
defaultItem<Item>::default_value();
关于c++ - 在 C++ 中根据模板参数的类型初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382413/