此问题在此处已有答案:
Explicit specialization in non-namespace scope does not compile in GCC(2个答案)
10天前关闭。
我有一个简单的模板类,里面有一个模板方法:
#include <iostream>
#include <optional>
template <typename T>
class Test
{
public:
template <typename U>
std::optional<U> test() { return std::nullopt; }
std::optional<double> test() { return std::make_optional<double>(3.0); }
};
int main()
{
Test<int> t;
std::cout << t.test<int>().value_or(100) << " " << t.test<double>().value_or(100) << std::endl;
}
字符串
我想让程序打印100 3.0
或100 3
而不是100 100
。如何在Test
中专门化test
方法,使其返回值为3.0
的非空可选值?
除了上面提到的,我还尝试在特殊化之上添加template<>
。这会导致编译器错误(在GCC 9.4.0中运行gcc -std=c++17 test.cpp
):
test.cpp:11:14: error: explicit specialization in non-namespace scope ‘class Test<T>’
11 | template<>
|
型
1条答案
按热度按时间kxeu7u2r1#
您可以通过以下方式将
test
专门化为double
:字符串
输出量:
型
更新:
此解决方案适用于MSVC,但不适用于GCC。查看更多信息here和here。
GCC的一个可能的解决方法是使用
if constexpr
而不是专门化:型