Many scholars believe this and other psalms labelled "of David," were not actually written by him. (See @Jack Douglas' answer for an opposing view.) For example, the Eerdmans Commentary on the Bible says of Psalm 138:
Both this psalm and the following seven psalms bear the title "Of David."
This is not intended, however, as an indication of authorship.
"Of David" is obviously not part of the original song but is a superscription added by a scribe. It could be that the editor believed the song to have been written by David, or that he understood it to be expressing the pious tradition that David represented.
The psalm's affirmation of Yahweh as the universal God (as opposed to Israel's particular deity) leads some commentators to conclude that it was written after the Exile, when Jews began to affirm that Yahweh was the God of all the nations. This interpretation is derived from verses such as "I will sing praises to You before the gods" and "All the kings of the earth will give thanks to You, O Lord." In David's time, neighboring kings were not expected to bow down to Israel's LORD. Israel must bow to other gods, but the idea of universal monotheism evolved later.
Conclusion: It is indeed is possible to affirm Davidic authorship of this psalm, either by saying he spoke prophetically or that he did not refer the Temple of Jerusalem when he said "temple." However it is also possible to interpret "of David" as a superscription of a later scribe which readers do not need to take literally.