【发布时间】:2020-07-08 08:40:30
【问题描述】:
我有以下代码:
#include <iostream>
#include <string>
#include <type_traits>
struct Foo
{
int i;
int j;
};
template<typename T, T DEFAULT>
class Bar
{
public:
Bar(): mVal(DEFAULT)
{
std::cout << "Bar constructor with mVal = " << mVal << "\n";
}
~Bar(){}
Bar(const T &i) : mVal(i)
{
std::cout << "Bar constructor with mVal = " << mVal << "\n";
}
Bar &operator=(T const &val)
{
mVal = val;
std::cout << "Bar assignment operator with mVal = " << mVal << "\n";
return *this;
}
explicit operator T() const
{
return mVal;
}
private:
T mVal;
};
int main()
{
std::cout << "Hello \n";
Bar<int, 10> bar1;
}
只要Bar 中的第一个模板参数是整数类型,这在 gcc C++14 中就可以正常工作。如果我想做Bar<Foo, {}>,则会打印以下错误消息:
on-type template parameters of class type only available with '-std=c++2a' or '-std=gnu++2a'
我已经预料到了。将 template<typename T, T DEFAULT> class Bar 更改为 template<typename T, T DEFAULT = {}> class Bar 会导致相同的错误。
同样的原因,模板专业化 template<typename T> class Bar<T, {}> 也不起作用。
我也尝试过使用std::enable_if_t<std::is_integral<T>::value>,但找不到可行的解决方案。
有没有什么方法可以只写Bar<Foo> 而不必为它写一个像template<typename T, T DEFAULT> class BarDefault 和template<typename T> class Bar 这样的单独的类?
【问题讨论】: