3

標準 C++11 でオプションの参照を使用するためのトリックを見つけました。この手法は信頼性が高く、動作は C++ 標準に従って明確に定義されていると思いますか?

// Optional reference using C++11 
// V. Reverdy - 2013
#include <iostream>
#include <type_traits>

template <class T = int, class = typename std::enable_if<std::is_same<typename std::decay<T>::type, int>::value>::type>
void f(T&& n = T())
{
    std::cout<<"--------"<<std::endl;
    std::cout<<"is const = "<<std::is_const<T>::value<<std::endl;
    std::cout<<"is reference = "<<std::is_reference<T>::value<<std::endl;
    std::cout<<"is lvalue reference = "<<std::is_lvalue_reference<T>::value<<std::endl;
    std::cout<<"is rvalue reference = "<<std::is_rvalue_reference<T>::value<<std::endl;
    std::cout<<"--------"<<std::endl;
    n *= 2;
} 

int main(int argc, char* argv[])
{
    int n = 42;
    std::cout<<"n = "<<n<<std::endl;
    f();
    std::cout<<"n = "<<n<<std::endl;
    f(n);
    std::cout<<"n = "<<n<<std::endl;
    return 0;
}

結果は次のとおりです。

n = 42
--------
is const = 0
is reference = 0
is lvalue reference = 0
is rvalue reference = 0
--------
n = 42
--------
is const = 0
is reference = 1
is lvalue reference = 1
is rvalue reference = 0
--------
n = 84

liveworkspace : LWSで利用可能なすべてのコンパイラで動作するようです。

4

2 に答える 2

2

ワット。

まず、「達成」したことは、たとえばオーバーロードによってはるかに簡単に達成できます。そして第二に、それはオプションの参照とまったく同じではありません。オプションの参照は値であり、実行時に参照を含む場合と含まない場合があります。動作は明確に定義されていますが、望ましいものでもオプションのリファレンスでもありません。デフォルトの引数として一時変数への参照をバインドすることは、状況によっては便利ですが、オプションの参照からは 10 億マイルも離れています。

于 2013-03-13T13:40:46.197 に答える