Is it possible to pass a variable or a value returned by a function as a template argument.
Example:
QVariantHash options;
options.insert("fontStyle", fontStyleObject); // QFont fontStyleObject
options.insert("fontColor", fontColorObject); // QColor fontColorObject
Q_FOREACH(const QVariant &option, options){
qDebug() << option.value<option.typeName()>();
}
As you saw, I have passed option.typeName()
as a template argument and that method returns the type of the object as QString
.
I have already done that but there is an error message: error: C2974: 'QVariant::value': invalid template argument for 'T', type expected
.
Is it possible to pass a variable or a value returned by a function as a template argument? and if not, what's the alternative way to do that?
It's possible if the template has a non-type template parameter and the function call is a constant expression. For example
#include <type_traits>
constexpr int foo() {
return 42;
}
template <int x>
std::integral_constant<int, x> bar() { return {}; }
int main() {
bar<foo()>();
}
I think you don't need that at all, you can just use
T QVariant::value() const
you can feed the resulting T to qDebug() operator <<. You might need to define how you print your T, have a look at: http://doc.qt.io/qt-4.8/qdebug.html#writing-custom-types-to-a-stream
for ( auto const & option : options)
qDebug() << option.value(); //returns T automatically
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.