c++ - 错误 C2783 : could not deduce template argument for structure argument

标签 c++ templates compiler-errors initialization

我遇到错误 C2783。 我用类似结构的测试用例重现了错误。
这是测试用例:

#include <iostream>

namespace ns1 {
    template <class T> class class_1 {};
}

namespace ns2 {
    using namespace ns1;
    template <typename T> inline ns1::class_1<T> myfunc();

    template<typename T>
    inline ns1::class_1<T> myfunc() {
            int a,b;
            std::cin>>a;
            std::cin>>b;
            if(a<b) return true;
            else return false;
    }

}


namespace ns3 {
struct myStruct {
    ns1::class_1<double> var1;
    ns1::class_1<double> var2;
    myStruct ( const ns1::class_1<double>& cl0= ns2::myfunc<double>(),
                    const ns1::class_1<double>& cl1= ns2::myfunc<double>()): var1(cl0), var2(cl1) {};
    };
}

错误是:
错误 C2783:“ns1::class_1 ns2::myfunc(void)”:无法推断“T”的模板参数

另外我想知道为什么它在第 27 行(cl0)而不是第 28 行(对于 cl1)给出错误? 如果我尝试在某些函数上使用它,它可以正常工作,只在结构参数中使用时出错。

最佳答案

这是一个编译器错误。如果您将 myfunc 的内容替换为有效代码(如建议的那样),它仍然不起作用。有关错误的描述、状态(和确认),请参阅 Microsoft Connect .您可能会尝试使用辅助类型来进行参数推导(有效):

namespace ns1 {
    template <class T> class class_1 {
    public: class_1 (int a, int b){}
    };
}

namespace ns2 {
    template<class T> struct deduction_helper{};

    using namespace ns1;
    template <typename T> inline ns1::class_1<T> myfunc(deduction_helper<T>);

    template<typename T>
    inline ns1::class_1<T> myfunc(deduction_helper<T>) {
        int a,b;
        std::cin>>a;
        std::cin>>b;
        ns1::class_1<T> c(a,b); return c;
    }

}


namespace ns3 {
    struct myStruct {
        ns1::class_1<double> var1;
        ns1::class_1<double> var2;

        myStruct ( const ns1::class_1<double>& cl0= ns2::myfunc(ns2::deduction_helper<double>()),
                   const ns1::class_1<double>& cl1= ns2::myfunc(ns2::deduction_helper<double>())
                 ): var1(cl0), var2(cl1) {};
    };
}

int main()
{
    ns3::myStruct x;
}

注意由于辅助类型驻留在 ns2 中,您可以使用 ADL 而不是限定名称 myfunc

关于c++ - 错误 C2783 : could not deduce template argument for structure argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18958587/

相关文章:

c++ - 如何构建 VS 2010 的 C 运行时库?

python - Jinja2中的多个同名 block

c++ - "Retroactive Union"- 可以吗?

c++ - Node 插件编译错误

c++ - 指针问题 char **words;

c++ - 在 C++ 中拥有字符串资源有什么意义?

c++ - 如何在C++项目中包含一个包含的所有头文件?

c++ - 模板类特化与模板类

c++ - 虚函数机制引用虚构造函数

sql - Oracle SQL 开发人员 : If Exists Update Else Insert Missing Right Parenthesis Compiler Error