c++ - 无法在模板类型之间进行转换/转换(无法推断模板参数)

标签 c++ templates template-argument-deduction

在摆弄模板和 static_assert 时,我遇到了以下问题

(下面是一个简短的示例,问题是相同的)


template< size_t n >
struct W {
    class X {
        public:
            /* breaks normal constructor
            template< size_t o >
            X( typename W<o>::X & y ){
                static_assert( o < n , "bad");
            };
            */

            template< size_t m >
            operator typename W<m>::X() const { 
                static_assert( n < m , "bad");
                return W<m>::X();
            };
    };
};

void func( W<6>::X y ){}

int main() {
    W<5>::X x;

    // > error: conversion from ‘X<5>’ to non-scalar type ‘X<6>’ requested
    //W<6>::X y = x; 

    // > error: error: no matching function for call to ‘W<5>::X::operator W<6>::X()
    // > note:   template argument deduction/substitution failed:
    // > note:   couldn’t deduce template parameter ‘m’
    //x.operator W<6>::X();

    // >  error: no matching function for call to ‘W<6>::X::X(W<5>::X&)’
    // > note:   template argument deduction/substitution failed:
    // > note:   couldn’t deduce template parameter ‘o’
    //static_cast< W<6>::X >(x);
    // similarly
    //( W<6>::X ) x;

    // End Goal:
    // > error: could not convert ‘x’ from ‘X<5>’ to ‘X<6>’
    func( x );
}

简单地说,我希望能够转换/转换 W<n>::X反对 W<m>::X仅当 n < m 时才对象.

一些补充说明

  • 我无法使用 X<n> 形式的类而不是W<n>::X
  • W::X<n> 的构造函数将是私有(private)的

最佳答案

根本问题是,在嵌套类型中,无法推导模板参数。如果您提供一个辅助变量(在我的示例中为 N )并为转换运算符使用更通用的模板,则可以解决该问题。您可以过滤掉其他类型,如 W<n>::X如果需要,请与 SFINAE 合作。

我们开始:

template< size_t n >
struct W {
    class X {
        public:
            // helper to get template parameter because it can't be deduced
            static constexpr size_t N = n; 

            template < typename T, size_t x=T::N >
                operator T() const 
                {
                    //static_assert( x < n , "bad");
                    std::cout << "Target: " << n << " Source " << x << std::endl;
                    return T(); 
                }

            X()=default;
    };   
};


void func( W<6>::X  ){}  

int main() {
    W<5>::X x;
    W<6>::X y=x; 
    x.operator W<6>::X();
    static_cast< W<6>::X >(x);
    ( W<6>::X ) x; 
    func( x ); 
}

关于c++ - 无法在模板类型之间进行转换/转换(无法推断模板参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71793094/

相关文章:

javascript - 删除 html 模板实例

java - C++ 中的模板、Java 中的泛型和 >> 位移运算符

c++ - Visual Studio 2012 中的奇怪错误

c++ - 我可以从它包含的数据中分离一个 std::vector<char> 吗?

c++ - 将输入值与 vector 中的值进行比较

c++ - 由于常量不一致导致模板参数推导失败

c++11 - init-list-as-function-argument 和模板的重载解析存在语义错误

c++ - 嵌套类构造函数中的父模板参数推导

c++ - 如何在容器中存储(空)分配器而不占用大小?

c++ - 是否有支持内置对象序列化的 C++ 编译器或附加组件?