4

これが私がやろうとしていることの例です(これは問題を説明するための「テスト」ケースです):

#include <iostream>
#include <type_traits>
#include <ratio>

template<int Int, typename Type> 
constexpr Type f(const Type x)
{
    return Int*x;
}

template<class Ratio, typename Type, 
         class = typename std::enable_if<Ratio::den != 0>::type>
constexpr Type f(const Type x)
{
    return (x*Ratio::num)/Ratio::den;
}

template</*An int OR a type*/ Something, typename Type>
constexpr Type g(const Type x)
{
    return f<Something, Type>(x);
}

int main()
{
    std::cout<<f<1>(42.)<<std::endl;
    std::cout<<f<std::kilo>(42.)<<std::endl;
}

ご覧のとおり、f()関数には2つのバージョンがあります。1つint目はテンプレートパラメーターとしてを取り、2つ目はを取りますstd::ratio。問題は次のとおりです。

この関数を「ラップ」して、最初のテンプレートパラメータとしてORg()を取り、の適切なバージョンを呼び出すことができます。intstd::ratiof()

g()2つの関数を書かずにそれを行う方法は?言い換えれば、私は代わりに何を書かなければならないの/*An int OR a type*/ですか?

4

3 に答える 3

2

これが私がそれをする方法です、しかし私はあなたのインターフェースを少し変えました:

#include <iostream>
#include <type_traits>
#include <ratio>

template <typename Type>
constexpr
Type
f(int Int, Type x)
{
    return Int*x;
}

template <std::intmax_t N, std::intmax_t D, typename Type>
constexpr
Type
f(std::ratio<N, D> r, Type x)
{
    // Note use of r.num and r.den instead of N and D leads to
    //   less probability of overflow.  For example if N == 8 
    //   and D == 12, then r.num == 2 and r.den == 3 because
    //   ratio reduces the fraction to lowest terms.
    return x*r.num/r.den;
}

template <class T, class U>
constexpr
typename std::remove_reference<U>::type
g(T&& t, U&& u)
{
    return f(static_cast<T&&>(t), static_cast<U&&>(u));
}

int main()
{
    constexpr auto h = g(1, 42.);
    constexpr auto i = g(std::kilo(), 42.);
    std::cout<< h << std::endl;
    std::cout<< i << std::endl;
}

42
42000

ノート:

  1. テンプレートパラメータを介してコンパイル時定数を渡さないことを利用しましたconstexpr(これが目的です)。constexpr

  2. g今では完璧なフォワーダーです。ただしstd::forward、マークアップされていないため使用できませんでしたconstexpr(おそらくC ++ 11の欠陥)。そこで、static_cast<T&&>代わりに使用するためにドロップダウンしました。ここでは、完全な転送は少しやり過ぎです。しかし、完全に精通していることは良いイディオムです。

于 2012-11-04T18:01:14.553 に答える
1

2つのg()関数を記述せずにそれを行う方法は?

あなたはそうしない。C ++では、オーバーロードを除いて、型またはある型の値を取得する方法はありません。

于 2012-11-04T17:22:13.917 に答える
0

型と非型の両方の値をとるテンプレートパラメータを持つことはできません。

解決策1:

オーバーロードされた関数。

解決策2:解決策2:

タイプに値を格納できます。元:

template<int n>
struct store_int
{
    static const int num = n;
    static const int den = 1;
};

template<class Ratio, typename Type, 
         class = typename std::enable_if<Ratio::den != 0>::type>
constexpr Type f(const Type x)
{
    return (x*Ratio::num)/Ratio::den;
}

template<typename Something, typename Type>
constexpr Type g(const Type x)
{
    return f<Something, Type>(x);
}

ただし、このソリューションでは、g<store_int<42> >(...)代わりに指定する必要がありますg<42>(...)

関数が小さい場合は、オーバーロードを使用することをお勧めします。

于 2012-11-04T17:27:46.850 に答える