c++ 模板化类中模板化方法的特殊化[重复]

qni6mghb  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(94)

此问题在此处已有答案

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.0100 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<>
      |

kxeu7u2r

kxeu7u2r1#

您可以通过以下方式将test专门化为double

#include <iostream>
#include <optional>

template <typename T>
class Test
{
public:
    template <typename U>
    std::optional<U> test() { return std::nullopt; }

    // Specialization for double:
    template <>
    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


更新:
此解决方案适用于MSVC,但不适用于GCC。查看更多信息herehere
GCC的一个可能的解决方法是使用if constexpr而不是专门化:

template <typename T>
class Test
{
public:
    template <typename U>
    std::optional<U> test() 
    { 
        if constexpr (std::is_same_v<U, double>)
        {
            return std::make_optional<double>(3.0);
        }
        return std::nullopt; 
    }
};

相关问题