在 C++ 中初始化依赖于模板参数类型的变量

Initializing a variable dependent on type in template parameter in C++

我有一个 class 和一个静态常量变量,我需要根据模板参数中的变量类型进行不同的初始化。有没有办法在没有专业化的情况下做到这一点?

在我的头文件中我有:

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 还是 string。但是,在上面的代码中我得到了一个 "cast from 'const char' to 'int' loses precision [-fpermissive]" 错误。

提供一个使用可以专门化的单独助手 class 的示例,而不必专门化整个模板 class,因为您提到过您希望看到这样的示例方法。

只需声明一个设置默认值的单独模板 class,并将其专门用于 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 定义相同的特化。

然后,您的主要 class 只需将 EMPTY_QUEUE 定义为:

template<typename Item>
const Item CircularQueue<Item>::EMPTY_QUEUE =
           defaultItem<Item>::default_value();