4

非型のテンプレート引数を推測しようとしています。

#include <iostream>

template <unsigned int S>
void getsize(unsigned int s) { std::cout << s << std::endl; }

int main()
{
  getsize(4U); 
// Id like to do this without explicitly stating getsize<4U>(4);
// or even getsize<4U>(); 
// Is this possible?
}

しかし、私はエラーが発生しています:

deduce_szie_t.cpp: In function 'int main()':
deduce_szie_t.cpp:9:15: error: no matching function for call to 'getsize(unsigned int)'
deduce_szie_t.cpp:9:15: note: candidate is:
deduce_szie_t.cpp:4:6: note: template<unsigned int <anonymous> > void getsize(unsigned int)
deduce_szie_t.cpp:4:6: note:   template argument deduction/substitution failed:
deduce_szie_t.cpp:9:15: note:   couldn't deduce template parameter '<anonymous>'

テンプレート パラメータを明示的に指定しなくても、unsigned int を推測できますか?

次のようにクリーンにしたい: getsize(4U) 次の記述は避けたい: getsize<4U>()

助けてくれてありがとう

4

3 に答える 3

5

関数の引数から型以外のテンプレート引数を推測することは可能ですが、希望する方法ではできません。これは、値からではなく、関数の引数の型からのみ推測できます。

例えば:

template <unsigned int S>
void getsize(int (*s)[S]) {
    std::cout << "pointer value: " << (void*)s << std::endl;
    std::cout << "deduced size: " << S << std::endl;
}

getsize(static_cast<int (*)[4]>(0));
于 2012-09-20T15:49:20.847 に答える
1

4次のコードは、数値を最小限の回数言及しています。

template <unsigned int N>
void getsize()
{
    std::cout << N << std::endl;
}

int main()
{
    getsize<4>();
}

数を 1 回未満言及することはできません。

于 2012-09-20T15:34:40.313 に答える
1

これを行うと何か問題があります(これがあなたが望んでいることだと思いますか??)

#include <iostream>

template<typename Ty>
void getsize(Ty t) { std::cout << t << std::endl; };

int main(int argc, char *argv[])
{
    getsize(4U);
    return 0;
}
于 2012-09-20T15:34:44.027 に答える