为什么编译器不能从条件类类型参数中推断出模板参数?[复制]

Why can't the compiler deduce a template parameter from a conditional class type argument? [duplicate]

提问人:Benjamin Bihler 提问时间:7/21/2023 更新时间:7/21/2023 访问量:40

问:

我很惊讶这段代码无法编译:

#include <type_traits>

template <int number, bool isTest1>
class TestClass1
{
};

template <int number, bool isTest1>
class TestClass2
{
};

template <int number, bool isTest1>
using MyTestClass = typename std::conditional<true, TestClass1<number, isTest1>, TestClass2<number, isTest1>>::type;

template <int number, bool isTest1>
auto createTest() -> MyTestClass<number, isTest1>
{
    return MyTestClass<number, isTest1>();
}

template <int number, bool isTest1>
auto function(int something, const MyTestClass<number, isTest1>& test) -> int
{
    return number;
}

int main()
{
    const MyTestClass<2, true> test = createTest<2, true>();
    function(123, test);

    // This works:
    // function<2, true>(123, test);

    return 0;
}

错误消息为:

main.cpp:31:23: error: no matching function for call to 'function(int, MyTestClass<2, true>&)'
   31 |     function(123, test);
      |                       ^
main.cpp:23:6: note: candidate: 'template<int number, bool isTest1> int function(int, MyTestClass<number, isTest1>&)'
   23 | auto function(int something, const MyTestClass<number, isTest1>& test) -> int
      |      ^~~~~~~~
main.cpp:23:6: note:   template argument deduction/substitution failed:
main.cpp:31:23: note:   couldn't deduce template parameter 'number'
   31 |     function(123, test);
      |                       ^

请参阅编译器资源管理器:https://godbolt.org/z/71avfordM

我很惊讶,因为似乎一切都是为了模板参数推导。我看不出任何歧义或任何东西。编译器有充分的理由拒绝我的代码吗?

C++ 条件语句 模板参数演绎

评论


答: 暂无答案