如何获得两种不同类型的乘积的结果类型,即
template< typename TA, typename TB>
struct multiplier
{
using result_type = // something here finds result of TA * TB
result_type operator()( TA a, TB b ) const
{
return a * b;
}
};
Run Code Online (Sandbox Code Playgroud)
我知道在C ++中将两个不同类型的数值相乘是完全有效的,这将给出编译器已知的类型的值。即将a double和an 相乘int将得到double类型答案。
这样,在编译时知道类型的模板类中,应该可以确定将要创建的类型。实际上,可以创建一个lambda来返回该值的结果,即
auto foo = [](int a, float b){ return a * b;}
auto c = foo( 13, 42.0 );
Run Code Online (Sandbox Code Playgroud)
这将导致c成为float。
请注意,我仅限于只能使用c ++ 11或更低版本的功能。
如果我有一个模板类定义为:
#ifndef A_HPP
#define A_HPP
template<class T>
class A
{
public:
int doSomething(int in, bool useFirst);
private:
template<int CNT>
class B
{
public:
int doSomething(int in);
};
B<2> first;
B<3> second;
};
#include "a_imp.hpp"
#endif
Run Code Online (Sandbox Code Playgroud)
现在我可以A::doSomething在这样的实现头文件中进行声明
#ifndef A_IMP_HPP
#define A_IMP_HPP
template<class T>
int A<T>::doSomething(int in, bool useFirst)
{
if (useFirst)
return first.doSomething(in);
return second.doSomething(in);
}
#endif
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何为子类的方法做声明.是否可能或者我必须做其他两种方法中的一种我可以想到这样做,即在主标题中定义方法或在A之外声明类.
请注意我正在使用C++ 11,所以如果这只是可行的,它仍然适用于我,虽然C++ 98解决方案对其他人有好处.
如果我有一个已知类型的变量或成员,是否有一种方法可以静态转换为所述类型而无需明确说明类型?
因此,确保将来如果变量类型发生变化,只需重新编译即可。
一个非常基本的例子是:
int y = 5;
uint32_t x;
x = static_cast< TYPEOF( x ) >( foo );
Run Code Online (Sandbox Code Playgroud)
现在,如果在未来的某个时刻 x 需要更改为 int64_t 的话,如果只需要更改变量的声明而不是所有 static_cast 行(可能有很多行),那就太好了。
作为个人说明,我正在使用 g++ 6 进行编译,因此我能够使用 c++14 功能,尽管与其他版本兼容的答案可能会让其他人受益。