c ++调用模板类的特定模板构造函数 [英] c++ call specific template constructor of template class

查看:526
本文介绍了c ++调用模板类的特定模板构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果类是模板,可以调用带有模板参数的构造函数。

Is it possible to call a constructor with template arguments if the class is a template too?

#include <stdio.h>
#include <iostream>

template <class A>
struct Class
{
  template <class B>
  Class(B arg) { std::cout << arg << std::endl; }
};

int main()
{
  Class<int> c<float>(1.0f);
  Class<int>* ptr = new Class<int><float>(2.0f);
  return 0;
}

编辑:所以我想调用特定模板构造函数的唯一方法是使用casted paramterers调用你想要的模板类型:

edit: so I guess the only way to call a specific template constructor is to call it with casted paramterers to the template type you want:

#include <stdio.h>
#include <iostream>

template <class A>
struct Class
{
  template <class B>
  Class(B arg) { std::cout << arg << std::endl; }

  Class(double arg) { std::cout << "double" << std::endl; }
  Class(float arg) { std::cout << "float" << std::endl; }
};

int main()
{
  Class<int> c(1.0f);
  Class<int>* ptr = new Class<int>((double)2.0f);
  return 0;
}

//输出:
float
double

// this outputs: float double

edit2:但是构造函数模板参数本身不是构造函数参数本身的一部分会发生什么?

template <class B, class C>
Class(B arg) { /* how do you specify ?? C */ }


推荐答案


edit2:但是构造函数模板参数不是构造函数参数本身的一部分会发生什么?

edit2: but what happens to constructor template arguments that are not part of the constructor arguments itself ?

template<typename T> struct encodeType { };

struct A {
  template<typename T, typename U>
  A(T t, encodeType<U>) { }
};

A a(1, encodeType<float>());

这篇关于c ++调用模板类的特定模板构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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