C ++如何在类型扣除不可能时调用模板化构造函数 [英] C++ how to call templated constructor when type deduction impossible

查看:163
本文介绍了C ++如何在类型扣除不可能时调用模板化构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译此代码没有问题:

  struct A 
{
template< typename T> ;
void f(int){}
};

A a;
a.f< double>(42);但是,类似的带有模板构造函数的代码不能编译:


$ b


  struct A 
{
template< typename T>
A(int){}
};

A a< double>(42);

Gcc在最后一行中出现以下错误: 'token



有没有办法使构造函数示例工作?

解决方案

没有办法为构造函数显式指定模板,因为你不能为构造函数命名。



根据你想做什么,这可以使用:

  #include< iostream> 
#include< typeinfo>

struct A
{
template< typename T>
struct with_type {};

template< typename T>
A(int x,with_type< T>)
{
std :: cout< x:<< x<< '\\\
'
<< T:<< typeid(T).name()<< std :: endl;
}
};

int main()
{
A a(42,A :: with_type< double>());
}

利用类型扣除功能欺骗。



这是一个非常不正式的方法,所以可能有更好的方法来做你需要的。


There are no problems compiling this code:

struct A
{
    template<typename T>
    void f(int) {}
};

A a;
a.f<double>(42);

However, similar code with templated constructor does not compile:

struct A
{
    template<typename T>
    A(int) {}
};

A a<double>(42);

Gcc gives the following error in the last line: error: unexpected initializer before '<' token

Is there a way to make constructor example work?

解决方案

There is no way to explicitly specify templates for a constructor, as you cannot name a constructor.

Depending on what you're trying to do, this can be used:

#include <iostream>
#include <typeinfo>

struct A
{
    template <typename T>
    struct with_type {};

    template<typename T>
    A(int x, with_type<T>)
    {
        std::cout << "x: " << x << '\n'
                  << "T: " << typeid(T).name() << std::endl;
    }
};

int main()
{
    A a(42, A::with_type<double>());
}

This "cheats" by taking advantage of type deduction.

This is quite unorthodox, though, so there's probably a better way of doing what you need.

这篇关于C ++如何在类型扣除不可能时调用模板化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆