【问题标题】:specify nested template parameters for function call为函数调用指定嵌套模板参数
【发布时间】:2018-01-30 00:39:12
【问题描述】:

调用模板函数时如何指定类型?

#include <string>
#include <utility>
#include <boost/variant.hpp>

template <typename O, typename E, template <typename, typename> class VariantType>
VariantType<O, E> f(O o)
{
    return VariantType<O, E>{std::move(o)};
}

int main()
{
    boost::variant<int, std::string> res = 
     f<int, std::string, boost::variant<int, std::string>>(17);
}

clang 报这样的错误(clang++ -Wall -std=c++11 test.cpp):

test.cpp: error: no matching function for call to 'f'
                boost::variant<int, std::string> res = f<int, std::string, boost::variant<int, std::string>>(17);
                                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.cpp: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'VariantType'
VariantType<O, E> f(O o)

【问题讨论】:

    标签: c++ c++11 boost


    【解决方案1】:

    boost::variant 模板类模板参数列表的数量不是两个。所以,修复它,例如通过将template &lt;typename, typename&gt; 更改为template &lt;typename...&gt;

    Live On Coliru

    #include <string>
    #include <utility>
    #include <boost/variant.hpp>
    
    template <typename O, typename E, template <typename...> class VariantType>
    VariantType<O, E> f(O o)
    {
        return VariantType<O, E>{std::move(o)};
    }
    
    int main()
    {
        boost::variant<int, std::string> res = f<int, std::string, boost::variant>(17);
    }
    

    【讨论】:

      【解决方案2】:

      你没有。将模板模板参数template &lt;typename, typename&gt; class VariantType 声明为f 的第三个模板参数意味着f 的第三个模板参数应该是一个类模板boost::variant 是一个模板。 boost::variant&lt;int, std::string&gt; 不再是模板——它是模板的特化。

      【讨论】:

      • 所以不可能调用f这样的函数?
      • 很抱歉,f&lt;int, std::string, boost::variant&gt; 也不起作用。你能告诉我如何修复我的代码吗?
      • @user1244932 你应该把它作为一个新问题发布。
      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 2015-06-29
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多